package com.buwstudio.domain.utils;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


public class IDGeneratorUtil {



	public static synchronized String getUUID() {
		UUID uuid = UUID.randomUUID();
		String str = uuid.toString();
		String uuidStr = str.replace("-", "");
		return uuidStr.toUpperCase();
	}

	public static synchronized String getUUID(String name) {
		UUID uuid = UUID.nameUUIDFromBytes(name.getBytes());
		String str = uuid.toString();
		String uuidStr = str.replace("-", "");
		return uuidStr.toUpperCase();
	}

//	private static long num = 0;
	
//	public static synchronized long getLongId() {
//		String date = TimeUtil.getCurrentDatetime(TimeFormat.LONG_DATE_PATTERN_WITH_MILSEC_NO_BLANK);
//		System.out.println("原始id=" + date);
//		if (num >= 99)
//			num = 0l;
//		++num;
//		if (num < 10) {
//			date = date + 00 + num;
//		} else {
//			date += num;
//		}
//		return Long.valueOf(date);
//	}

	// 下面的19位UUID生成实现
	final static char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
			'9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
			'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
			'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',
			'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
			'Z' };

	final static Map<Character, Integer> digitMap = new HashMap<Character, Integer>();

	static {
		for (int i = 0; i < digits.length; i++) {
			digitMap.put(digits[i], (int) i);
		}
	}

	/**
	 * 支持的最大进制数
	 */
	private static final int MAX_RADIX = digits.length;

	/**
	 * 支持的最小进制数
	 */
	private static final int MIN_RADIX = 2;

	/**
	 * 将长整型数值转换为指定的进制数（最大支持62进制，字母数字已经用尽）
	 *
	 * @param i
	 * @param radix
	 * @return
	 */
	private static String toString(long i, int radix) {
		if (radix < MIN_RADIX || radix > MAX_RADIX)
			radix = 10;
		if (radix == 10)
			return Long.toString(i);

		final int size = 65;
		int charPos = 64;

		char[] buf = new char[size];
		boolean negative = (i < 0);

		if (!negative) {
			i = -i;
		}

		while (i <= -radix) {
			buf[charPos--] = digits[(int) (-(i % radix))];
			i = i / radix;
		}
		buf[charPos] = digits[(int) (-i)];

		if (negative) {
			buf[--charPos] = '-';
		}

		return new String(buf, charPos, (size - charPos));
	}

	private static NumberFormatException forInputString(String s) {
		return new NumberFormatException("For input string: \"" + s + "\"");
	}

	/**
	 * 将字符串转换为长整型数字
	 *
	 * @param s
	 *            数字字符串
	 * @param radix
	 *            进制数
	 * @return
	 */
	private static long toNumber(String s, int radix) {
		if (s == null) {
			throw new NumberFormatException("null");
		}

		if (radix < MIN_RADIX) {
			throw new NumberFormatException("radix " + radix
					+ " less than Numbers.MIN_RADIX");
		}
		if (radix > MAX_RADIX) {
			throw new NumberFormatException("radix " + radix
					+ " greater than Numbers.MAX_RADIX");
		}

		long result = 0;
		boolean negative = false;
		int i = 0, len = s.length();
		long limit = -Long.MAX_VALUE;
		long multmin;
		Integer digit;

		if (len > 0) {
			char firstChar = s.charAt(0);
			if (firstChar < '0') {
				if (firstChar == '-') {
					negative = true;
					limit = Long.MIN_VALUE;
				} else if (firstChar != '+')
					throw forInputString(s);

				if (len == 1) {
					throw forInputString(s);
				}
				i++;
			}
			multmin = limit / radix;
			while (i < len) {
				digit = digitMap.get(s.charAt(i++));
				if (digit == null) {
					throw forInputString(s);
				}
				if (digit < 0) {
					throw forInputString(s);
				}
				if (result < multmin) {
					throw forInputString(s);
				}
				result *= radix;
				if (result < limit + digit) {
					throw forInputString(s);
				}
				result -= digit;
			}
		} else {
			throw forInputString(s);
		}
		return negative ? result : -result;
	}


	private static String digits(long val, int digits) {
		long hi = 1L << (digits * 4);
		return toString(hi | (val & (hi - 1)), MAX_RADIX).substring(1);
	}

	/**
	 * 产生19位的UUID
	 * @return
	 */
	public static String getUUID19(){
		//产生UUID
		UUID uuid = UUID.randomUUID();
		StringBuilder sb = new StringBuilder();
		//分区转换
		sb.append(digits(uuid.getMostSignificantBits() >> 32, 8));
		sb.append(digits(uuid.getMostSignificantBits() >> 16, 4));
		sb.append(digits(uuid.getMostSignificantBits(), 4));
		sb.append(digits(uuid.getLeastSignificantBits() >> 48, 4));
		sb.append(digits(uuid.getLeastSignificantBits(), 12));
		return sb.toString();
	}
	
    public static String getUUID22() {
        Encoder encoder = Base64.getUrlEncoder();
        // Create random UUID
        UUID uuid = UUID.randomUUID();
        // Create byte[] for base64 from uuid
        byte[] src = ByteBuffer.wrap(new byte[16])
                .putLong(uuid.getMostSignificantBits())
                .putLong(uuid.getLeastSignificantBits())
                .array();
        // Encode to Base64 and remove trailing ==
        return encoder.encodeToString(src).substring(0, 22);
    }
    
    public static void main(String[] args) {  
//    	List<String> tmp = new ArrayList<>();
//    	long count = 10000000L;
//        long time = System.currentTimeMillis();  
//        for (int i=0; i<count; i++) {  
//        	String tmpid = getUUID19();
//        	tmp.add(tmpid);	
//        	
//        }  
//        System.out.println(System.currentTimeMillis() - time + "ms");
//        if(tmp.size()==count){
//        	System.out.println("未重复"); 	
//        }
        
//        
//        long time1 = System.currentTimeMillis();  
//        for (int i=0; i<1000000L; i++) {  
//        	getUUID();  
//        }  
//        System.out.println(System.currentTimeMillis() - time1);
    	
//		long time2 = System.currentTimeMillis();
//		for (int i = 0; i < 1000000L; i++) {
//			getUUID22();
//		}
//		System.out.println(System.currentTimeMillis() - time2);
		for (int i = 0; i < 10; i++) {
			System.out.println(getUUID19());
			System.out.println(getUUID22());
		}
    }  
}
